package org.thingsboard.server.config.annotation;

import org.springframework.http.RequestEntity;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;


public class Demo{


    public static String encryptSHA(String method, String resource, String systemCode, long utcTime, int nonce,
                                    String secretKey) throws NoSuchAlgorithmException {
        StringBuilder srcStr = new StringBuilder();
        srcStr.append(method);
        srcStr.append(resource);
        srcStr.append("?systemCode=");
        srcStr.append(systemCode);
        srcStr.append("&timestamp=");
        srcStr.append(utcTime);
        srcStr.append("&nonce=");
        srcStr.append(nonce);
        // 请求方法 +请求路径 + ?+系统编码+utc时间戳+随机正整数
        String signature = sha256(srcStr.toString(), secretKey);
        return signature;
    }

    public static String sha256(String input, String salt) throws NoSuchAlgorithmException {
        MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
        mDigest.update(salt.getBytes());
        byte[] result = mDigest.digest(input.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    public static long getUTC() {
        // 1、取得本地时间：
        Calendar cal = Calendar.getInstance();
        // 2、取得时间偏移量：
        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
        // 3、取得夏令时差：
        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
        // 4、从本地时间里扣除这些差量，即可以取得UTC时间：
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
        return cal.getTimeInMillis();
    }
}

